package models

import (
	"fmt"
	"time"

	"gorm.io/gorm"
)

// User 用户模型
type User struct {
	ID        uint           `json:"id" gorm:"primaryKey;autoIncrement"`
	Username  string         `json:"username" gorm:"uniqueIndex;not null;size:100"`
	Email     string         `json:"email" gorm:"uniqueIndex;not null;size:255"`
	Password  string         `json:"-" gorm:"not null;size:255"` // 不返回给前端
	Phone     *string        `json:"phone_number" gorm:"size:20"`
	Avatar    *string        `json:"avatar" gorm:"size:500"`
	Status    string         `json:"status" gorm:"default:active;size:20"`
	Role      string         `json:"role" gorm:"default:user;size:20"`
	LastLogin *time.Time     `json:"last_login" gorm:"type:datetime(3)"`
	CreatedAt time.Time      `json:"created_at" gorm:"type:datetime(3)"`
	UpdatedAt time.Time      `json:"updated_at" gorm:"type:datetime(3)"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index;type:datetime(3)"` // 软删除
}

// TableName 指定表名
func (User) TableName() string {
	return "tb_users"
}

// VerificationCode 验证码模型
type VerificationCode struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement"`
	Phone     string    `json:"phone" gorm:"not null;size:20;index"`
	Code      string    `json:"code" gorm:"not null;size:10"`
	Type      string    `json:"type" gorm:"not null;size:20;default:login"` // login, register, etc.
	Used      bool      `json:"used" gorm:"default:false"`
	ExpiresAt time.Time `json:"expires_at" gorm:"not null;type:datetime(3)"`
	CreatedAt time.Time `json:"created_at" gorm:"type:datetime(3)"`
	UpdatedAt time.Time `json:"updated_at" gorm:"type:datetime(3)"`
}

// TableName 指定表名
func (VerificationCode) TableName() string {
	return "tb_verification_codes"
}

// IsExpired 检查验证码是否过期
func (vc *VerificationCode) IsExpired() bool {
	return time.Now().After(vc.ExpiresAt)
}

// UserSession 用户会话模型
type UserSession struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement"`
	UserID    uint      `json:"user_id" gorm:"not null;index"`
	Token     string    `json:"token" gorm:"not null;size:500;uniqueIndex"`
	ExpiresAt time.Time `json:"expires_at" gorm:"not null;type:datetime(3)"`
	CreatedAt time.Time `json:"created_at" gorm:"type:datetime(3)"`
	User      User      `json:"user" gorm:"foreignKey:UserID"`
}

// TableName 指定表名
func (UserSession) TableName() string {
	return "tb_user_sessions"
}

// IsExpired 检查会话是否过期
func (us *UserSession) IsExpired() bool {
	return time.Now().After(us.ExpiresAt)
}

// CreateUserRequest 创建用户请求
type CreateUserRequest struct {
	Username string `json:"username" binding:"required,min=3,max=50"`
	Email    string `json:"email" binding:"required,email"`
	Phone    string `json:"phone" binding:"required,min=11,max=11"`
	Password string `json:"password" binding:"required,min=6"`
}

// SendCodeRequest 发送验证码请求
type SendCodeRequest struct {
	PhoneNumber string `json:"phone_number" binding:"required,min=11,max=11"`
}

// VerifyCodeRequest 验证码验证请求
type VerifyCodeRequest struct {
	PhoneNumber    string `json:"phone_number" binding:"required"`
	Code           string `json:"code" binding:"required,len=6"`
	VerificationID string `json:"verification_id" binding:"required"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Success bool      `json:"success"`
	Message string    `json:"message"`
	Data    LoginData `json:"data,omitempty"`
}

// LoginData 登录数据
type LoginData struct {
	User      UserInfo `json:"user"`
	Token     string   `json:"token"`
	ExpiresIn int64    `json:"expires_in"` // 秒数
}

// UserInfo 用户信息（返回给前端的用户信息）
type UserInfo struct {
	ID          string  `json:"id"` // 改为字符串类型
	Username    string  `json:"username"`
	Email       string  `json:"email"`
	PhoneNumber string  `json:"phone_number"` // 确保不为nil
	Avatar      *string `json:"avatar"`
	Status      string  `json:"status"`
	Role        string  `json:"role"`
	Nickname    string  `json:"nickname"` // 确保不为nil
}

// ToUserInfo 转换为前端用户信息格式
func (u *User) ToUserInfo() UserInfo {
	// 确保字段不为nil
	phoneNumber := ""
	if u.Phone != nil {
		phoneNumber = *u.Phone
	}

	return UserInfo{
		ID:          fmt.Sprintf("%d", u.ID), // 转换为字符串
		Username:    u.Username,
		Email:       u.Email,
		PhoneNumber: phoneNumber,
		Avatar:      u.Avatar, // 保持原始指针，允许为nil
		Status:      u.Status,
		Role:        u.Role,
		Nickname:    u.Username, // 使用用户名作为昵称，确保不为nil
	}
}
